package com.letu.core.httpClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.annotation.processing.SupportedSourceVersion;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
public class PostHttpClient {
    private static CloseableHttpClient httpClient;

    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(builder.build(),
                    new String[]{"TLSv1", "TLSv1.2"}, null, new NoopHostnameVerifier());
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.
                    <ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslcsf)
                    .build();
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(2000);
            cm.setDefaultMaxPerRoute(20);
            httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslcsf)
                    .setConnectionManager(cm)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }


//        try {
//            SSLContext ctx = SSLContext.getInstance("TLS");
//
//            X509TrustManager tm = new X509TrustManager() {
//                @Override
//                public X509Certificate[] getAcceptedIssuers() {
//                    return null;
//                }
//
//                @Override
//                public void checkClientTrusted(X509Certificate[] arg0,
//                                               String arg1) throws CertificateException {
//                }
//
//                @Override
//                public void checkServerTrusted(X509Certificate[] arg0,
//                                               String arg1) throws CertificateException {
//                }
//            };
//            ctx.init(null, new TrustManager[]{tm}, null);
//            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
//                    ctx, NoopHostnameVerifier.INSTANCE);
////            CloseableHttpClient httpclient = HttpClients.custom()
////                    .setSSLSocketFactory(ssf).build();
//
//            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
//            cm.setMaxTotal(200);
//            cm.setDefaultMaxPerRoute(20);
//            httpClient = HttpClients.custom().setSSLSocketFactory(ssf).setConnectionManager(cm).build();
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


    }

    public static String postForm(String url, JSONObject params) {
        log.info(String.format("postForm is execute %s", url));
        if (params == null) {
            log.info("params is null");
            return null;
        }
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        //参数
        try {
            Header[] headers = new Header[]{new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString())};
//            StringEntity stringEntity = new StringEntity(params.toJSONString(), "utf-8");
            StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params, SerializerFeature.WriteMapNullValue), "utf-8");

            // 根据开源中国的请求需要，设置post请求参数
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
            httpPost.setHeaders(headers);
            // 执行请求
            response = httpClient.execute(httpPost);
            log.info(String.format("postForm code is  %s ", response.getStatusLine().getStatusCode()));

            // 解析响应，获取数据
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (200 == response.getStatusLine().getStatusCode()) {
                log.info(String.format("postForm content is %s", content));
                return content;
            }
            log.info(String.format("postForm content is %s ", content));

        } catch (Exception e) {
            e.printStackTrace();
            log.info(covertStackTraceToString(e));
            System.out.println(covertStackTraceToString(e));
            log.info(String.format("Exception  is execute  %s ", covertStackTraceToString(e)));
        } finally {
            httpPost.releaseConnection();
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("result  is null ");
        return null;
    }


    public static String postForm(String url, JSONObject params, Map<String, String> headerMap) {
        log.info(String.format("postForm is execute %s", url));
        if (params == null) {
            log.info("params is null");
            return null;
        }
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        //参数
        try {
            Header[] headers = null;
            if (headerMap == null) {
                headers = new Header[]{new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString())};
            } else {
                headers = new Header[headerMap.size() + 1];
                headers[0] = new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
                int i = 1;
                for (String key : headerMap.keySet()) {
                    headers[i++] = new BasicHeader(key, headerMap.get(key));
                }
            }


            StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params, SerializerFeature.WriteMapNullValue), "utf-8");
            // 根据开源中国的请求需要，设置post请求参数
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
            httpPost.setHeaders(headers);
            // 执行请求
            response = httpClient.execute(httpPost);
            log.info(String.format("postForm code is  %s ", response.getStatusLine().getStatusCode()));

            // 解析响应，获取数据
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (200 == response.getStatusLine().getStatusCode()) {
                log.info(String.format("postForm content is %s", content));
                return content;
            }
            log.info(String.format("postForm content is %s ", content));

        } catch (Exception e) {
            e.printStackTrace();
            log.info(covertStackTraceToString(e));
            System.out.println(covertStackTraceToString(e));
            log.info(String.format("Exception  is execute  %s ", covertStackTraceToString(e)));
        } finally {
            httpPost.releaseConnection();
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("result  is null ");
        return null;
    }


    public static String covertStackTraceToString(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }


    /**
     * from表单
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPostForm(String url, Map<String, String> params) {
        if (params == null) {
            return null;
        }
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        //参数
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
            Header[] headers = new Header[]{new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")};
            StringEntity stringEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.setHeaders(headers);
            // 执行请求
            response = httpClient.execute(httpPost);
            if (200 == response.getStatusLine().getStatusCode()) {
                // 解析响应，获取数据
                String content = EntityUtils.toString(response.getEntity(), "GBK");
                log.info("post调用结果:{}" + content);
                return content;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


}
